package mis510.homefinders;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import mis510.homefinders.Map.JavaScriptInterface;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class Basic_info extends Activity {
	 static String search_address = null;
	 Button bk_btn;
	 TextView binfo_address;
	 Intent nextActivity;
	
	String result;
    private static final DocumentBuilderFactory dbFac;
    private static final DocumentBuilder docBuilder;
    ArrayList<String> info = new ArrayList<String>();
    ListView info_list;
	ArrayAdapter<String> arrayAdapter;
    
    static
    {
        try
        {
            dbFac = DocumentBuilderFactory.newInstance();
            docBuilder = dbFac.newDocumentBuilder();
        }
        catch(ParserConfigurationException e)
        {
            throw new RuntimeException(e);
        }
    }
    private static final String DEEP_URL = "http://www.zillow.com/webservice/GetDeepSearchResults.htm";
    //private static final String ZESTIMATE_URL = "http://www.zillow.com/webservice/GetZestimate.htm";
    private static final String ZWSID = "X1-ZWz1bhef5il5hn_6o78e";
    //private static final NumberFormat nf = NumberFormat.getCurrencyInstance();
  	private static String lastupdatedT = null;
	private static String amountT = null;
	private static String currency_amt = null;
	private static String street_url = null;
	private static String cs_url = null;

	
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.basic_info);
	        System.out.println("binfo");
	        
	        
	        Intent intent = this.getParent().getIntent();
			Bundle bundle = intent.getExtras();
			search_address = bundle.getString("address");
			System.out.println("passed address in binfo tab: "+search_address);
			
	        binfo_address = (TextView) findViewById(R.id.binfo_address);
			binfo_address.setText(search_address);
			
			
			WebView myWebView = (WebView) findViewById(R.id.b_info);
	        WebSettings webSettings = myWebView.getSettings();
	        webSettings.setJavaScriptEnabled(true);
	        webSettings.setBuiltInZoomControls(false);
	        myWebView.setWebChromeClient(new WebChromeClient());
	        final JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(this);  
	        myWebView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
	        myWebView.loadUrl("http://54.214.11.178:8080/HomeFinders/weather_mobile.html");
	        
	        bk_btn = (Button)findViewById(R.id.bk_btn);
	        bk_btn.setOnClickListener(new View.OnClickListener() {
	            @Override
	            public void onClick(View view) {
	            	nextActivity = new Intent(Basic_info.this, SearchProperty.class);
	            	startActivity(nextActivity);
	            }
	        });
	    
			info_list = (ListView)findViewById(R.id.info_list);
			arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_item, info);
			//info_list.setAdapter(arrayAdapter); 
			System.out.println("listview setup");
			new Zillow().execute(search_address);
	    }
			
			
	    
	    public class JavaScriptInterface {
			Context mContext;
			Basic_info address_binfo = new Basic_info();
	 		String address_send = address_binfo.search_address;
		    JavaScriptInterface(Context c) {
		        mContext = c;
		    }
		    
		    @JavascriptInterface
		    public String getAddress(){	    	
		    	//final String msgeToast = webMessage;
		    	System.out.println("search_address: "+search_address);
		    	System.out.println("address_send: "+address_send);
		    	return address_send;
//		    	 myHandler.post(new Runnable() {
//		             @Override
//		             public void run() {
//		                 // This gets executed on the UI thread so it can safely modify Views
//		                 myTextView.setText(msgeToast);
//		             }
//		         });

		       //Toast.makeText(mContext, webMessage, Toast.LENGTH_SHORT).show();
		    }
	    }
			
			
	    
	    
	    
	    public class Zillow extends AsyncTask<String, Void, ArrayList<String>>
	    {
	    	
	    	//ProgressDialog dialog;

//	        @Override
//	        protected void onPreExecute() {
//	            dialog = new ProgressDialog(Zillow.this);
//	            dialog.setTitle("Calculating...");
//	            dialog.setMessage("Please wait...");
//	            dialog.setIndeterminate(true);
//	            dialog.show();
//	        }


	        // Returns Zestimate value for address.
	    	protected ArrayList<String> doInBackground(String...search_address)
	        {
	    		System.out.println("in B INFO zillow");
	    		String[] search_address_bg = search_address;
	    		System.out.println("IN BINFO search_address: "+search_address_bg[0]);
	    		StringTokenizer st = new StringTokenizer(search_address_bg[0], ",");
	    		String street = st.nextToken().trim();
	    		System.out.println("st"+street);
	    		try {
					street_url = URLEncoder.encode(street, "utf-8");
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	    		System.out.println("st_url"+street_url);
	    		String city = st.nextToken().trim();	    		
	    		String state = st.nextToken().trim();
	    		String cityStateZip = city+" "+state;
	    		System.out.println("c and s"+cityStateZip);
	    		try {
					cs_url = URLEncoder.encode(cityStateZip, "utf-8");
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	    		System.out.println("IN B INFO parsed address: "+ street+cityStateZip);
	            Document deepDoc;
	    		try {
	    			deepDoc = docBuilder.parse(DEEP_URL + 
	    			                                "?zws-id=" + ZWSID + 
	    			                                "&address=" + street_url + 
	    			                                "&citystatezip=" + cs_url
	    			                                +"&rentzestimate=true");
	            System.out.println("URL :"+DEEP_URL + 
	                                            "?zws-id=" + ZWSID + 
	                                            "&address=" + street_url + 
	                                            "&citystatezip=" + cityStateZip
	                                            +"&rentzestimate=true");
	            

//	            Element root = deepDoc.getDocumentElement();
//	            String item = root.getElementsByTagName("message").item(0).getNodeValue().toString();
//	            System.out.println("item:"+item);
	            
	            Element statuscode = (Element)deepDoc.getElementsByTagName("message").item(0);
	            System.out.println("code: "+statuscode);
	            if (statuscode != null)
	            {
	            	String code = statuscode.getElementsByTagName("code").item(0).getTextContent();
	            	if (code.equals("0"))
            	  {
	            		String zpid = null;
	            		String yearbuiltT = null;
	            		String lotsizeT = null;
	            		String bathroomsT = null;
	            		String bedroomsT = null;
	            		String lastsolddateT = null;
	            		String reg_name = null;
	        			String overview_link = null;
	        			String lowest = null;
	        			String currency_low = null;
	        			String highest = null;
	        			String currency_high = null;
	        			
	            		Element firstResult = (Element)deepDoc.getElementsByTagName("result").item(0);
	            		if (firstResult != null)
	                    {
	            			zpid = firstResult.getElementsByTagName("zpid").item(0).getTextContent();
	            			System.out.println("Zpid  "+zpid);
	            
	                    }
	            		Element yearbuilt = (Element)deepDoc.getElementsByTagName("yearBuilt").item(0);
	            		if (yearbuilt != null)
	            		{
	            			yearbuiltT = yearbuilt.getTextContent(); 
	            			System.out.println("Year Built  "+yearbuiltT);
	            			info.add("Year Built  "+yearbuiltT);
	            		}
	            		Element lotsize = (Element)deepDoc.getElementsByTagName("lotSizeSqFt").item(0);
	            		if (lotsize != null)
	            		{
	            			lotsizeT = lotsize.getTextContent(); 
	            			System.out.println("Lot size  "+lotsizeT+" SqFt");
	            			info.add("Lot size  "+lotsizeT+" SqFt");
	            		}
	            		Element bathrooms = (Element)deepDoc.getElementsByTagName("bathrooms").item(0);
	            		if (bathrooms != null)
	            		{
	            			bathroomsT = bathrooms.getTextContent(); 
	            			System.out.println("Bathrooms  "+bathroomsT);
	            			info.add("Bathrooms  "+bathroomsT);
	            		}
	            		Element bedrooms = (Element)deepDoc.getElementsByTagName("bedrooms").item(0);
	            		if (bedrooms != null)
	            		{
	            			bedroomsT = bedrooms.getTextContent(); 
	            			System.out.println("Bedrooms  "+bedroomsT);
	            			info.add("Bedrooms  "+bedroomsT);
	            		}
	            		Element lastsolddate = (Element)deepDoc.getElementsByTagName("lastSoldDate").item(0);
	            		if (lastsolddate != null)
	            		{
	            			lastsolddateT = lastsolddate.getTextContent(); 
	            			System.out.println("Last sold date  "+lastsolddateT);
	            			info.add("Last sold date  "+lastsolddateT);
	            		}
	            		Element rentzestimate = (Element)deepDoc.getElementsByTagName("rentzestimate").item(0);
	            		if (rentzestimate != null)
	            		{
	            			Element amount = (Element)rentzestimate.getElementsByTagName("amount").item(0);
	            			if (amount != null)
	            			{
	            				amountT = amount.getTextContent();
	            				currency_amt = amount.getAttribute("currency");
	            			}
	            			Element lastupdated = (Element)rentzestimate.getElementsByTagName("last-updated").item(0);
	            			if (lastupdated != null)
	            			{
	            				lastupdatedT = lastupdated.getTextContent();
	            			}
	            			System.out.println("Average Price (updated "+lastupdatedT+") "+amountT+" "+currency_amt);
	            			info.add("Average Price (updated "+lastupdatedT+") "+amountT+" "+currency_amt);
	            			Element valuationRange = (Element)rentzestimate.getElementsByTagName("valuationRange").item(0);
	            			if (valuationRange != null)
	            			{
	            				Element low = (Element)valuationRange.getElementsByTagName("low").item(0);
	            				Element high = (Element)valuationRange.getElementsByTagName("high").item(0);
	            				if ((low != null) && (high != null))
	            				{	 
	            					lowest = low.getTextContent();
	            					currency_low = low.getAttribute("currency");
	            					highest = high.getTextContent();
	            					currency_high = amount.getAttribute("currency");
	            					System.out.println("Price range "+lowest+" "+currency_low+" to "+highest+" "+currency_high);
	            					info.add("Price range "+lowest+" "+currency_low+" to "+highest+" "+currency_high);
	            				}
	            			}
	            		}
	            		Element region = (Element)deepDoc.getElementsByTagName("region").item(0);
	            		Element overview = (Element)deepDoc.getElementsByTagName("overview").item(0);
	            		if ((region != null) && (overview != null))
	            		{
	            			reg_name = region.getAttribute("name");
	            			overview_link = overview.getTextContent();
	            			System.out.println("Real Estate  "+reg_name);
	            			System.out.println("Overview  "+overview_link);
	            			info.add("Real Estate  "+reg_name);
	            			info.add("Overview  "+overview_link);
	            		}
	            		
//	    				result = "Year Built: "+yearbuiltT+System.getProperty("line.separator")+ "Lot size: " +lotsizeT+" SqFt" + System.getProperty("line.separator") + "Number of Bathrooms: "+ bathroomsT +System.getProperty("line.separator")+"Number of Bedrooms:"+bedroomsT+System.getProperty("line.separator")+ "Last sold date:   "+lastsolddateT +System.getProperty("line.separator")+ "Average Rental Price (updated "+lastupdatedT+") "+amountT+" "+currency_amt +System.getProperty("line.separator")+ "Rental Price range "+lowest+" "+currency_low+" to "+highest+" "+currency_high + System.getProperty("line.separator") + "RealEstate: " + reg_name +System.getProperty("line.separator") +  "Overview: " + overview_link;
//	    				System.out.println(result);
	            	}
	            	else 
	            	{
	            	//System.out.println(statuscode.getElementsByTagName("text").item(0).getTextContent());
	            	//result = statuscode.getElementsByTagName("text").item(0).getTextContent();
	            		result = "Error: no exact match found for input address";
	            		info.add(result);
	            	}
	            
	            //result = code;
	            }
	            else
	            {
	            	result = "Error: no exact match found for input address";
            		info.add(result);
	            }
//	            System.out.println(result);
//	            return info;
	        }
	    	 catch (SAXException e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		} catch (IOException e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}
	    		//info.add("Error: no exact match found for input address");
	    		return info;
	        }
	    	
	    	protected void onPostExecute(ArrayList<String> info) {
	    		System.out.println("postexecute");
	    		for (int i = 0; i < info.size(); i++) {
	    		     System.out.println(info.get(i));
	    		}
				info_list.setAdapter(arrayAdapter); 	    		
	    		
	        }
	    	
	    	
	    }
}

	    
